import logging

from django.http import HttpResponse
from django.http import JsonResponse

from celery_tasks.sms.tasks import ccp_send_sms_code

logger = logging.getLogger('django')
# Create your views here.
import random
from django.views import View
from meiduo.libs.captcha.captcha import captcha

from django_redis import get_redis_connection
# 图形验证码
class ImageCodeView(View):
    def get(self,request,uuid):

        # 调用工具生成图形验证码

        text,imag = captcha.generate_captcha()
        # 链接redis
        redis_conn = get_redis_connection("verify_code")
        redis_conn.setex("img_%s" % uuid, 300, text)
        return HttpResponse(imag,content_type='image/jpg')
# 短信验证码
class SMSCodeView(View):
    def get(self,request,mobile):
        image_code = request.GET.get("image_code")
        uuid = request.GET.get("image_code_id")
        if not all([image_code,uuid]):
            return JsonResponse({'code':400,
                                 'errmsg':'缺少参数'})
        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return JsonResponse({'code':400,
                                 'errmsg': '发送短信频繁'})
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return JsonResponse({'code':400,
                                 'errmsg':'验证码失效'})
        # 删除验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)
        image_code_server = image_code_server.decode()
        if image_code_server.lower() != image_code.lower():
            return JsonResponse({'code':400,
                                 'errmsg':'图形验证码有误'})
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0,999999)
        print(sms_code)
        # 创建管道对象
        p1 = redis_conn.pipeline()

        p1.setex('sms_%s' % mobile,
                         300,
                         sms_code)
        p1.setex("send_flag_%s" % mobile,60,1)
        p1.execute()
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        # 使用celery
        ccp_send_sms_code.delay(mobile,sms_code)
        return  JsonResponse({'code':0,
                              'errmsg':'短信发送成功'})